package net.tv90.shoppingserver.service;

import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import net.tv90.shoppingserver.dao.UserRepository;
import net.tv90.shoppingserver.exception.ServerException;
import net.tv90.shoppingserver.model.domain.User;
import net.tv90.shoppingserver.model.dto.UserRegisterDTO;
import net.tv90.shoppingserver.util.Assert;
import net.tv90.shoppingserver.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class UserService {

    @Autowired
    UserRepository userRepository;

    Map<Integer, User> loginUser = new ConcurrentHashMap<>();

    public void login(String username, String password) {
        Assert.assertNotNull("用户名不能为空", HttpStatus.BAD_REQUEST, username);
        Assert.assertNotNull("密码", HttpStatus.BAD_REQUEST, username);
        String encryptedPwd = SecurityUtils.sha256Encrypt(password);
        User user = userRepository.findUserByUsernameAndPassword(username, encryptedPwd);
        Assert.assertNotNull("用户名或密码错误", HttpStatus.UNAUTHORIZED, user);
        log.info("{}登录成功", user.getUsername());
        StpUtil.login(user.getId());
    }

    public void register(UserRegisterDTO dto) {
        Assert.assertNotNull("用户名不能为空", HttpStatus.BAD_REQUEST, dto.getUsername());
        Assert.assertNotNull("密码不能为空", HttpStatus.BAD_REQUEST, dto.getPassword());
        Assert.assertNotNull("邮箱不能为空", HttpStatus.BAD_REQUEST, dto.getEmail());
        User user = userRepository.findUserByUsernameOrEmail(dto.getUsername(), dto.getEmail());
        Assert.assertNull("该用户名或邮箱已存在", HttpStatus.UNAUTHORIZED, user);
        log.info("{}注册成功", dto.getUsername());
        User registered = User.builder()
                .username(dto.getUsername())
                .password(SecurityUtils.sha256Encrypt(dto.getPassword()))
                .email(dto.getEmail())
                .role(0)
                .status(0)
                .build();
        userRepository.save(registered);
    }

    public void logout() {
        Integer id = StpUtil.getLoginIdAsInt();
        User user = userRepository.findById(id)
                .orElseThrow(() -> new ServerException("该用户不存在", HttpStatus.BAD_REQUEST));
        log.info("{}登出成功", user.getUsername());
        loginUser.remove(id);
        StpUtil.kickout(user.getId());
    }

    public String getCurrentUserName() {
        if (!StpUtil.isLogin()) {
            return null;
        }
        int id = StpUtil.getLoginIdAsInt();
        if (!loginUser.containsKey(id)) {
            User user = userRepository.findById(id)
                    .orElseThrow(() -> new ServerException("该用户不存在", HttpStatus.BAD_REQUEST));
            loginUser.put(id, user);
            return user.getUsername();
        }
        return loginUser.get(id).getUsername();
    }
}
